<template>
  <div>
    <!-- 头部导航 -->
    <van-nav-bar
      title="京东登录"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <!-- 表单 -->
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="username"
          name="用户名"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="password"
          type="current-password"
          name="密码"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          登录
        </van-button>
      </div>
    </van-form>
    <!-- 注册 -->
    <div class="register">
      <span>去注册 </span>
      <p @click="$router.push('/register')">
        <span>快速注册</span>
        <van-icon name="arrow" />
      </p>
    </div>
  </div>
</template>

<script>
import { userLogin } from "../server/user.js";
export default {
  data() {
    return {
      username: "",
      password: "",
    };
  },
  methods: {
    onClickLeft() {
      this.$router.go(-1);
    },
    onSubmit() {
      userLogin({ loginname: this.username, password: this.password }).then(
        (res) => {
          if (res.code === "200") {
            this.username = "";
            this.password = "";
            this.$store.commit("setuserid", res.data.userid);
            this.$store.commit("settoken", res.data.token);
            localStorage.setItem("token", res.data.token);
            localStorage.setItem("userInfo", JSON.stringify(res.data));
            this.$router.push("/home");
          } else {
            console.log(res.message);
          }
        }
      );
    },
  },
};
</script>

<style scoped>
.van-form {
  margin-top: 1.875rem;
}
.register {
  margin: 20px;
}
.register > span {
  color: #666;
  font-size: 0.875rem;
  display: block;
}
.register > p {
  width: 100%;
  height: 2.8125rem;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 1.25rem;
  box-sizing: border-box;
  border-radius: 0.3125rem;
  background-color: #fff;
  margin: 0.3125rem 0 0;
  color: #666;
}
</style>
